const {Book} = require('../../models/Books');

module.exports = async (req, res) => {
    //获取客户端传递的参数：跳过查询条数
    var skipNum = parseInt(req.query.skipNum)
    try{
        //根据二级分类名查询图书信息
        const book = await Book.find({secondCategory: req.query.cateName},
            {'ISBN':1,"author":1,"title":1,"img":1,"publisher":1,"pubdate":1}).
            limit(7).skip(skipNum).lean();
            if(book.length == 0){
                res.send({errCode:"0",msg:"请求成功",data:{category:book}})
            }
            //根据ISBN联合查询商品信息集合对应ISBN的商品信息
            let opt = [{$lookup:{
                        from: "commodities",
                        localField: "ISBN",
                        foreignField: "ISBN",
                        as: "books"},},
                {$project:{
                        "books.ISBN":1,
                        "books.customPrice":1, //商品价格
                    }},
                {$skip:skipNum},
                {$limit:7},        //限制查询7条
                {$unwind:"$books"},
                {$group:{
                   _id:{ISBN:"$books.ISBN"},
                   minPrice:{$min:"$books.customPrice"}}
                }
            ]
            for(let i=0;i<book.length;i++){
                let optArr = [].concat(opt);
                optArr.splice(0,0,{$match:{"ISBN":book[i].ISBN}})
                //聚合查询商品信息
                 Book.aggregate(optArr,(err,data)=>{
                     if(err){
                         res.status(500).send({errCode:"1",msg:"服务器内部错误"})
                     }else{
                        if(data.length !== 0){
                            for(let j=0; j < book.length;j++){
                              if(book[j].ISBN == data[0]._id.ISBN){
                              //加入最低价
                               book[j].minPrice = data[0].minPrice
                              }
                            }
                        }
                        if(i == book.length-1){
                            //返回数据
                            res.send({errorCode:"0",msg:"success",data:{category:book}});
                         }  
                     }
                 })
             } 
    }catch(e){
        res.status(500).send({errCode:"1",msg:"服务器内部错误"})
    }
}